// A $( document ).ready() block.
$( document ).ready(function() {
    updateCitiesDropdown();

    //Verifica se ja existe um cpe seleccionado.
    if(!(sessionStorage.getItem("cpe_id") === null )){
        // mostrar navigation bar
        document.getElementById('esconde').style.display = 'block';
        document.getElementById('esconde_tabelas').style.display = 'block';
        document.getElementById('cpe-info').style.display = 'block';
        //document.getElementById('cpe-info').style.display = 'block';
        //document.getElementById('cpe-alerts').style.display = 'block';
        
    }
    else{
        //document.getElementById('cpe-info').style.display = 'none';
        $('#alert_cpe').html('<div class="alert alert-warning" role="alert"> Please Select a CPE ... </div>');
        document.getElementById('alert_php').style.display = 'none';
        document.getElementById('notice_php').style.display = 'none';
        //$('#selected_cpe').html('<div class="alert alert-info" role="alert"> Please Select a CPE ... </div>');
        //document.getElementById('cpe-alerts').style.display = 'none';
    }
});

//DEBUG, LOCAL STORAGE FOR CHART! CURRENT CPE_ID
//document.getElementById("myText").value = "Current CPE_ID = " + sessionStorage.getItem("cpe_id");

// esconder a dropdown das ruas 
document.getElementById('ruas_list').style.display = 'none';

// esconder a dropdown das juntas 
//document.getElementById('juntas_list').style.display = 'none';

// esconder a dropdown das cpes
document.getElementById('cpes_list').style.display = 'none';


//esconder cpe_info
//document.getElementById('cpe-info').style.display = 'none';
//esconder cpe_alertas
//document.getElementById('cpe-alerts').style.display = 'none';


//Joao Rodrigues - Search CPE
function searchResult(el)
{
    var text_input_value = $("#" + el + "")[0].value;

    switch(el) {
        case "searchByZip":
            searchByZip(text_input_value)
            break;
        case "searchByMac":
            searchByMac(text_input_value)
            break;
        default:
            alert("Error: Case error searchBy");
    }
}

//Joao Rodrigues - Search CPE
function searchByZip(zip){

    var request = $.ajax({
            type:"POST",
            url:"webservs/get_data.php",
            data: {
                method: "get_cpe_info_by_zip",
                zip_code: zip
            },
            dataType: "json",
            error: function (xhr, status, error) {  alert ("erro: " + xhr.responseText); }
    });

    request.done( function (data){                    
        mostrar_graficos(data.cpe_id, data.mac, data.ssid);
    });
}

//Joao Rodrigues - Search CPE
function searchByMac(mac){

    var request = $.ajax({
            type:"POST",
            url:"webservs/get_data.php",
            data: {
                method: "get_cpe_info_by_mac",
                mac_address: mac
            },
            dataType: "json",
            error: function (xhr, status, error) {  alert ("erro: " + xhr.responseText); }
    });

    request.done( function (data){                    
        mostrar_graficos(data.cpe_id, data.mac, data.ssid);
    });

}  


//Joao Rodrigues - SmartSearchByZipCode---------------------------------------------------------------------
var availableTagsZip = [];

function smartSearchByZipCode(zip){
    
    var request = $.ajax({
        type:"POST",
        url:"webservs/get_data.php",
        data: {
            method: "get_cpes_zip_by_zip",
            zip_code: zip
        },
        dataType: "json",
        error: function (xhr, status, error) {  alert ("erro smartseachbyzipcode: " + xhr.responseText); }
    });

    request.done( function (data){
        availableTagsZip = Object.keys(data);
                   
    });
};

$("#searchByZip").keypress(function(key){

    if(key.which == 13) {
        searchResult("searchByZip");
    }

    smartSearchByZipCode(this.value);

    $("#searchByZip").autocomplete({
        source: availableTagsZip
    });
});


//Joao Rodrigues - SmartSearchByMacAddress-------------------------------------------------------------------
var availableTagsMac = [];

function smartSearchByMacAddress(mac){
    
    var request = $.ajax({
        type:"POST",
        url:"webservs/get_data.php",
        data: {
            method: "get_cpes_mac_by_mac",
            mac_address: mac
        },
        dataType: "json",
        error: function (xhr, status, error) {  alert ("erro smartsearchbymacaddress: " + xhr.responseText); }
    });

    request.done( function (data){
        availableTagsMac = Object.keys(data);
                   
    });
};

$("#searchByMac").keypress(function(key){

    if(key.which == 13) {
        searchResult("searchByMac");
    }

    smartSearchByMacAddress(this.value);

    $("#searchByMac").autocomplete({
        source: availableTagsMac
    });
});

//Joao Rodrigues - Dropdown City-------------------------------------------------------------------------------------------------------------------------------------------
$("#list_cities_dropdown").click(function(){

});

function updateCitiesDropdown(){
    var list_cities_dropdown = $('#list_cities_dropdown');
    list_cities_dropdown.empty();

    var request = $.ajax({
        type:"POST",
        url:"webservs/get_data.php",
        data: {
            method: "get_all_cities"
        },
        dataType: "json",
        error: function (xhr, status, error) {  alert ("erro updatecitiesdropdown: " + xhr.responseText); }
    });

    request.done( function (data){
        console.log(data);
        $.each(data, function(i, city){
            list_cities_dropdown.append("<li role='presentation'><a role='menuitem' tabindex='-1' onclick=updateStreetDropdown('" + city + "');>"+city+"</a></li>");            
        });
    });
};

function updateTownDropdown(city_name){
    //TODO;
};

function updateStreetDropdown(city_name){
    $("#dropdownMenu1 > span").html("<span>" + city_name +" <span class='caret'></span></span>" ); //Mostra o texto escolhido na dropdown das cidades.
    $("#list_ruas_dropdown").empty();
    document.getElementById('ruas_list').style.display = 'block';

    var request = $.ajax({
        type:"POST",
        url:"webservs/get_data.php",
        data: {
            method: "get_streets_by_city",
            city: city_name
        },
        dataType: "json",
        error: function (xhr, status, error) {  alert ("erro updatestreetsdropdown: " + xhr.responseText); }
    });

    request.done( function (data){
        console.log(data);
        $.each(data, function(i, street){
            var street_name_encoded = window.btoa(street[0]); //Encode base64 - para prevenir illegal token
            //street[0] = nome da rua, street[1] = zip
            $("#list_ruas_dropdown").append("<li role='presentation'><a role='menuitem' tabindex='-1' onclick=updateCpeDropdown('" + street_name_encoded + "');>"+street[0]+"</a></li>");
            //$("#list_ruas_dropdown").append("<li role='presentation'><a role='menuitem' tabindex='-1' onclick=temp('" + street[1] + "');>"+street[0]+"</a></li>");
        });
    });
};

//Funcao TEMPORARIA ate decisao de dropdown town
function temp(zip){
    alert(zip);
    searchByZip(zip);
}

function updateCpeDropdown(street_name){

    $("#list_cpes_dropdown").empty();
    
    var street_name_decoded =  window.atob(street_name); //Fazer decode de base64- para prevenir illegal token

    $("#dropdownMenu3").html("<span>" + street_name_decoded +" <span class='caret'></span></span>" ); //Mostra o texto escolhido na dropdown das ruas.

    document.getElementById('cpes_list').style.display = 'block';
    var request = $.ajax({
            type:"POST",
            url:"webservs/get_data.php",
            data: {
                method: "get_cpes_by_street",
                street: street_name_decoded
            },
            dataType: "json",
            error: function (xhr, status, error) {  alert ("erro: " + xhr.responseText); }
    });

    request.done( function (data){
        console.log(data);
        //NOTA: $.each(data, function(key, value){
        $.each(data, function(i, cpe){
            //cpe[0] = cpe_id, cpe[1] = mac, cpe[2] = ssid
            $("#list_cpes_dropdown").append("<li role='presentation'><a role='menuitem' tabindex='-1' onclick='mostrar_graficos( "+cpe[0]+" , \"" +cpe[1]+"\" , \""+cpe[2]+"\" ); changeCpeDropdownLabel(\""+cpe[2]+"\"); '> " + cpe[2] +"</a></li>");
        });

        //mostrar_graficos(data.cpe_id, data.mac, data.ssid);
        //sessionStorage.setItem("cpe_id", data.cpe_id);
        //alert("Changed localstorage cpe_id to: " + sessionStorage.getItem("cpe_id"));
    });
    
}

//funcao TEMPORARIA para mostrar cpe na dropdown CPES
function changeCpeDropdownLabel(ssid){
    $("#dropdownMenu4").html("<span>" + ssid +" <span class='caret'></span></span>" ); //Mostra o texto escolhido na dropdown das cpe.
}



//Joao Rodrigues - Mostrar Graficos--------------------------------------------------------
function mostrar_graficos(cpe_id, mac, ssid){

    //define localstorage do cpe_id
    sessionStorage.setItem("cpe_id", cpe_id);

    var request = $.ajax({
            type:"POST",
            url:"webservs/get_data.php",
            data: {
                method: "get_cpe_full_info",
                cpe_id: cpe_id
            },
            dataType: "json",
            error: function (xhr, status, error) {  alert ("errogetcpefullinfo: " + xhr.responseText); }
    });

    request.done( function (data){
        //definicao de localstorage dos restantes minutos
        sessionStorage.setItem("cpe_mac",                 data.mac);
        sessionStorage.setItem("cpe_ssid",                data.ssid);
        sessionStorage.setItem("cpe_zip",                 data.zip);
        sessionStorage.setItem("cpe_street",              data.street);
        sessionStorage.setItem("cpe_city",                data.city);
        sessionStorage.setItem("cpe_wlan_channel",        data.wlan_channel);
        sessionStorage.setItem("cpe_wlan_status",         data.wlan_status);
        sessionStorage.setItem("cpe_wlan_enable",         data.wlan_enable);
        sessionStorage.setItem("cpe_wlan_radioenable",    data.wlan_radioenable);
        sessionStorage.setItem("cpe_wlan_standard", "802.11 " + data.wlan_standard);
        sessionStorage.setItem("cpe_wlan_channelmode",    data.wlan_channelmode);
        sessionStorage.setItem("cpe_wlan_ssidadvert",     data.wlan_ssidadvert);
	sessionStorage.setItem("cpe_access",     	  data.access);
        //location.reload() //Reload da Pagina
	window.location="index.php";
    });
  
}
